﻿using KeaoBase;
using System.Net;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System;
using DataCenter_DataBase;

namespace DataCenter.Models.WeiXin
{
    public class WeiXinComm
    {
        public static bool CheckSign(HttpContext Context, string Token)
        {
            string signature = KeaoHttpUtils.HttpGetStringParam(Context, "signature");
            string timestamp = KeaoHttpUtils.HttpGetStringParam(Context, "timestamp");
            string nonce = KeaoHttpUtils.HttpGetStringParam(Context, "nonce");

            if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce))
            {
                return false;
            }

            List<string> a = new List<string>();
            a.Add(Token);
            a.Add(timestamp);
            a.Add(nonce);
            a.Sort();

            string tmpStr = string.Format("{0}{1}{2}", a[0], a[1], a[2]);
            tmpStr = KeaoUtils.GetSha1Str(tmpStr).ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public static string GetWeiXinAccessToken()
        {
            try
            {
                if (KeaoRedis.ContainsKey("weixin_access_token"))
                {
                    return KeaoRedis.ReadString("weixin_access_token");
                }
                else
                {
                    try
                    {
                        WeiXinUtils.WeiXinBase weiXinBase = new WeiXinUtils.WeiXinBase(SysConfig._Config.appid, SysConfig._Config.secret);
                        KeaoRedis.WriteString("weixin_access_token", weiXinBase.access_token, weiXinBase.expires_in);
                        return weiXinBase.access_token;
                    }
                    catch
                    {
                        return string.Empty;
                    }
                }
            }
            catch(Exception err)
            {
                KeaoUtils.LogTxt(string.Format("获取微信access_token异常。{0}",err.Message));
                return string.Empty;
            }
        }

        public static WeiXinUser GetWeiXinUserByOpenId(string OpenId)
        {
            try
            {
                string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN ", GetWeiXinAccessToken(), OpenId);
                string readStr = string.Empty;
                readStr = KeaoBase.KeaoHttpUtils.Get(tokenUrl);
                WeiXinUser wUser = KeaoUtils.Json2Obj<WeiXinUser>(readStr);
                return wUser;
            }
            catch(Exception err)
            {
                KeaoUtils.LogTxt(string.Format("根据openid获取用户信息异常。{0}",err.Message));
                return null;
            }
        }

        public static void CreateWeiXinUser(object state)
        {
            try
            {
                ApiDataBase m_Api = new ApiDataBase();
                BaseWeiXinMsg obj = state as BaseWeiXinMsg;
                WeiXinUser weiXinItem = WeiXinComm.GetWeiXinUserByOpenId(obj.FromUserName);
                tbl_weixin_user userItem = new tbl_weixin_user();
                userItem.id = KeaoUtils.GetGUID();
                userItem.client_code = "";
                userItem.expires_time = DateTime.Today;
                userItem.openid = weiXinItem.openid;
                userItem.user_status = 0;
                userItem.weixin_headimgurl = weiXinItem.headimgurl;
                userItem.weixin_nickname = weiXinItem.nickname;
                m_Api._Db.tbl_weixin_user.Add(userItem);
                m_Api._Db.SaveChanges();
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("关注创建微信用户异常。{0}", err.Message));
            }
        }

    }
}